﻿using Microsoft.AspNetCore.SignalR.Client;
using Newtonsoft.Json;
using OConf.NetCore.Common;
using OConf.NetCore.Model;
using OConf.NetCore.Static;

namespace OConf.NetCore.SignalR
{
    public class SignalRClient
    {
        private static HubConnection connection;
        public static async void InitConfigClient(string serverAddr, string projectName, string secretKey)
        {
            string sign = string.Empty;
            if (!string.IsNullOrEmpty(secretKey))
            {
                SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
                dic.TryAdd("ProgramName", projectName);
                dic.TryAdd("Key", secretKey);
                sign = JsonConvert.SerializeObject(dic).MD5Encrypt32();
            }

            connection = new HubConnectionBuilder()
                .WithUrl($"{serverAddr}/chat?AppId={projectName}&Sign={sign}")
                .WithAutomaticReconnect(new RetryPolicy())
                .Build();

            connection.On<BackProgramConfigInfo>("ReceiveConfig", (configInfo) =>
            {
                try
                {
                    ConfigCommon.SaveConfigInfo(configInfo);
                }
                catch
                {
                }
            });

            try
            {
                await connection.StartAsync();
            }
            catch
            {
            }
        }
    }
}
